package net.openl10n.mdf;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import net.openl10n.document.api.IFragment;
import net.openl10n.mdf.immutable.ImmutableBuilder;
import net.openl10n.mdf.immutable.ImmutableStateException;

public class TextFlowBuilder extends AbstractDocumentPartBuilder implements ImmutableBuilder<TextFlow>{

	private List<IFragment> fragments;
	private List<PartId> children;
	
	private StringBuilder contentBuilder;
	
	public TextFlowBuilder() {
		super();
		fragments = new ArrayList<IFragment>();
		children = new ArrayList<PartId>();
		contentBuilder = new StringBuilder();
	}
	
	public TextFlowBuilder(TextFlow textFlow) {
		super(textFlow);
		this.fragments = new ArrayList<IFragment>(textFlow.getFragments());
		this.children = new ArrayList<PartId>(textFlow.getChildren());
		this.contentBuilder = new StringBuilder(textFlow.getContent());
	}

	public StringBuilder getContentBuilder() {
		return contentBuilder;
	}
	
	public String getContent() {
		return contentBuilder.toString();
	}
	
	public void setContent(String content) {
		contentBuilder.delete(0, contentBuilder.length());
		contentBuilder.append(content);
	}
	
	public List<IFragment> getFragments() {
		return fragments;
	}
	
	public void setFragments(List<IFragment> fragments) {
		this.fragments = fragments;
	}
	
	public boolean isValid() {
		if(! super.isValid()) return false;
		return fragments != null && children != null;
	}
	
	public void validate() throws ImmutableStateException {
		if(! isValid()) {
			Set<String> invalidFields = new LinkedHashSet<String>();
			super.populateInvalidFields(invalidFields);
			if(fragments == null)
				invalidFields.add("fragments");
			if(children == null)
				invalidFields.add("children");
			throw new ImmutableStateException(invalidFields);
		}
	}
	
	@Override
	public TextFlow build() throws ImmutableStateException{
		validate();
		return new TextFlow(id, version, getContent(), children, fragments);
	}	
}
